package com.xsd.prc;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @Description: 读写锁
 * @Author: zhoufuzong
 * @Created: 2021-01-03 12:14:23
 * @Version: 1.1.0
 */


class MyCache{
    private volatile Map<String,Object> map = new HashMap<>();

    private ReadWriteLock lock = new ReentrantReadWriteLock();

    public void put(String key,Object value){
        lock.writeLock().lock();
        System.out.println(Thread.currentThread().getName()+"\t 写入数据");

        try {
            Thread.sleep(300);
            map.put(key,value);
            System.out.println(Thread.currentThread().getName()+"\t 写入完成");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.writeLock().unlock();
        }

    }

    public void get(String key){
        lock.readLock().lock();
        try {
            System.out.println(Thread.currentThread().getName()+"\t 读取数据");
            Thread.sleep(300);
            System.out.println(Thread.currentThread().getName()+"\t读取数据完成"+map.get(key));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.readLock().unlock();
        }
    }
}

public class ReadWriteLockDemo {

    public static void main(String[] args) {
        MyCache myCache = new MyCache();

        for (int i = 1; i <=6 ; i++) {
            int finalI = i;
            new Thread(()->{
                myCache.put(finalI +"",finalI+"");
            },String.valueOf(i)).start();

        };

        for (int i = 1; i <=6 ; i++) {
            int finalI =i;
            new Thread(()->{
                myCache.get(finalI+"");
            },String.valueOf(i)).start();

        };
    }
}
